package com.weijing.pretty_app.fragment

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.FragmentSystemBinding
import com.weijing.pretty_app.dialog.UpgradeDialog
import com.weijing.pretty_app.util.BrightnessManager
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import com.weijing.pretty_app.util.ToastUtils
import com.weijing.pretty_app.util.VolumeManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.util.regex.Pattern

private const val TAG = "SystemFragment"

/**
 * 设置fragment页面
 */
class SystemFragment : Fragment() {

    private lateinit var binding: FragmentSystemBinding
    private val viewModel: SystemFragmentModel by viewModels()
    private var installFile: File? = null
    private var newVersionNum: String? = ""
    private var downLoadUrl: String? = ""

    companion object {
        const val INSTALL_PERMISS_CODE = 0x11
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentSystemBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.fragmentSystemSeekBar.setPadding(
            0, binding.fragmentSystemSeekBar.paddingTop,
            0, binding.fragmentSystemSeekBar.paddingBottom
        )
        binding.fragmentSystemSeekBarSound.setPadding(
            0, binding.fragmentSystemSeekBar.paddingTop,
            0, binding.fragmentSystemSeekBar.paddingBottom
        )

        setBrightness()
        setupVolumeSeekBar()

        SPUtil.getString(KeyUtil.SAVE_DEVICES_SN)?.let {
            binding.fragmentSystemTvSn.text = it
        }

        CoreUtil.getVersionName(requireContext()).let {
            binding.fragmentSystemIvVersion.text = "V：" + it
        }

        //更新apk按钮
        binding.fragmentSystemClUpdate.setOnClickListener {
            if (downLoadUrl.isNullOrEmpty() || newVersionNum.isNullOrEmpty()) return@setOnClickListener
            val upgradeDialog =
                UpgradeDialog(downLoadUrl!!, newVersionNum!!, object : UpgradeDialog.Callback {
                    override fun downLoadSuccess(filePath: String) {
                        //下载完成就自动安装
                        requireActivity().runOnUiThread {
                            ToastUtils.showLong(getString(R.string.Installing))
                        }
                        //自动安装
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            val readyInstallFile = File(filePath)
                            installFile = readyInstallFile
                            setInstallPermission(readyInstallFile)
                        } else {
                            installApk(File(filePath))
                        }
                    }
                })
            val tag = childFragmentManager.findFragmentByTag("upgradeDialog")
            if (tag == null) {
                upgradeDialog.show(childFragmentManager, "upgradeDialog")
            }
        }

        viewModel.getVersionNum()

        viewModel.numLiveData.observe(requireActivity()) { serverVersion ->
            serverVersion?.let {
                val localVersion = CoreUtil.getVersionName(requireContext())
                newVersionNum = serverVersion
                downLoadUrl = KeyUtil.BASE_DOWNLOAD_URL + "app-v${serverVersion}.apk"
                Log.i(TAG, "拼接下载的路径: ${downLoadUrl}")
                when (CoreUtil.compareVersions(localVersion, serverVersion)) {
                    1 -> {    //需要更新，有新版本
                        binding.fragmentSystemClUpdate.visibility = View.VISIBLE
                    }

                    0 -> {    //不需要更新，已经是最新版本
                        binding.fragmentSystemClUpdate.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun setBrightness() {
        val initialBrightness = getInitialBrightness()
        binding.fragmentSystemSeekBar.max = 100
        // 将0-1范围转换为SeekBar的0-100范围
        binding.fragmentSystemSeekBar.progress = (initialBrightness * 100).toInt()

        binding.fragmentSystemSeekBar.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 将 SeekBar 的值映射到 0-1 之间
                val brightness = progress / 100f
                // 设置当前 Activity 的亮度
                BrightnessManager.setScreenBrightness(requireActivity(), brightness)

                // 保存亮度设置
                BrightnessManager.saveBrightness(requireContext(), brightness)

                // 更新全局亮度
                BrightnessManager.setAppBrightness(brightness)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}

            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun getInitialBrightness(): Float {
        val savedBrightness = BrightnessManager.getSavedBrightness(requireContext())
        return if (savedBrightness >= 0f) {
            savedBrightness
        } else {
            getSystemBrightness(requireContext())
        }
    }

    // 获取当前系统亮度
    private fun getSystemBrightness(context: Context): Float {
        return try {
            val brightness = Settings.System.getInt(
                context.contentResolver, Settings.System.SCREEN_BRIGHTNESS
            )
            brightness / 255f  // 系统亮度的范围是0-255，将其转为0-1的浮动值
        } catch (e: Settings.SettingNotFoundException) {
            0.5f  // 如果无法获取亮度，则返回默认值50%
        }
    }

    private fun setupVolumeSeekBar() {
        val maxVolume = VolumeManager.getMaxVolume(requireContext())
        var currentVolume = VolumeManager.getSavedVolume(requireContext())

        if (currentVolume == -1) {
            currentVolume = VolumeManager.getCurrentSystemVolume(requireContext())
        }

        binding.fragmentSystemSeekBarSound.max = maxVolume
        binding.fragmentSystemSeekBarSound.progress = currentVolume

        binding.fragmentSystemSeekBarSound.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    VolumeManager.setSystemVolume(requireContext(), progress)
                    VolumeManager.saveVolume(requireContext(), progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    /**
     * 8.0以上系统设置安装未知来源权限
     */
    fun setInstallPermission(readyInstallFile: File) {
        val haveInstallPermission: Boolean
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先判断是否有安装未知来源应用的权限
            haveInstallPermission = requireContext().packageManager.canRequestPackageInstalls()
            if (!haveInstallPermission) {
                //弹框提示用户手动打开
                val messageDialog = AlertDialog.Builder(requireContext())
                    .setMessage(getString(R.string.need_permission))
                    .setPositiveButton("OK") { _, _ ->
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            //此方法需要API>=26才能使用
                            toInstallPermissionSettingIntent()
                        }
                    }
                val create = messageDialog.create()
                create.setOnShowListener {
                    val button = create.getButton(DialogInterface.BUTTON_POSITIVE)
                    val cancelButton = create.getButton(DialogInterface.BUTTON_NEGATIVE)
                    //设置确认按钮颜色
                    button.setTextColor(Color.parseColor("#FECB36"))
                    cancelButton.setTextColor(Color.parseColor("#4F4F4F"))
                }
                create.show()
            } else {
                installApk(readyInstallFile)
            }
        } else {
            installApk(readyInstallFile)
        }
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    private fun installApk(file: File) {
        Log.i("InstallApk", "path----- ${file.path}")
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val uri = FileProvider.getUriForFile(
                requireContext(), "com.weijing.pretty_app.fileProvider", file
            )
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        try {
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 开启安装未知来源权限
     */
    private fun toInstallPermissionSettingIntent() {
        val packageURI = Uri.parse("package:${requireContext().packageName}")
        val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
        startActivityForResult(intent, INSTALL_PERMISS_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == INSTALL_PERMISS_CODE) {
            if (installFile != null) {
                installApk(installFile!!)
            }
        }
    }
}

class SystemFragmentModel : ViewModel() {

    val numLiveData = MutableLiveData<String>()

    fun getVersionNum() {
        viewModelScope.launch {
            val serverVersion = withContext(Dispatchers.IO) { // 切换到 IO 线程执行网络请求
                try {
                    val client = OkHttpClient()
                    val request = Request.Builder()
                        .url(KeyUtil.BASE_DOWNLOAD_URL) // 生产环境务必改用 HTTPS！
                        .build()
                    val response = client.newCall(request).execute()
                    val html = response.body?.string() ?: ""

                    // 正则匹配版本号
                    val pattern = Pattern.compile("app-v(\\d+\\.\\d+)\\.apk")
                    val matcher = pattern.matcher(html)
                    if (matcher.find()) matcher.group(1) else null
                } catch (e: Exception) {
                    Log.e(TAG, "Network error: ${e.message}")
                    null
                }
            }

            // 回到主线程更新 UI
            serverVersion?.let { version ->
                Log.i(TAG, "Latest version: $version")
                numLiveData.postValue(version)
            }
        }
    }
}